<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/blockly/blockly.min.js"></script>
  <title>Blockly 变量列表模块</title>
</head>
<body>
  <div id="blocklyDiv" style="height: 480px; width: 600px;"></div>
  <xml id="toolbox" style="display: none">
    <block type="variable_list"></block>
  </xml>

  <script>
    // 定义变量列表块
    Blockly.defineBlocksWithJsonArray([
      {
        "type": "variable_list",
        "message0": "选择变量 %1",
        "args0": [
          {
            "type": "field_dropdown",
            "name": "VARIABLE",
            "options": [] // 动态填充
          }
        ],
        "output": "String",
        "colour": 230,
        "tooltip": "选择一个变量",
        "helpUrl": ""
      }
    ]);

    // 初始化工作区
    var workspace = Blockly.inject('blocklyDiv', {
      toolbox: document.getElementById('toolbox')
    });

    // 更新变量列表
    function updateVariableList() {
      var variableList = Blockly.Variables.allVariables(workspace);

      workspace.getAllBlocks().forEach(function(block) {
        if (block.type === 'variable_list') {
          var dropdownField = block.getField('VARIABLE');
          var options = variableList.map(function(variable) {
            return [variable, variable]; // 每个变量的名称和变量本身
          });
          dropdownField.updateOptions(options);  // 更新下拉框选项
        }
      });
    }

    // 监听工作区变化
    workspace.addChangeListener(function(event) {
      if (event.type === Blockly.Events.BLOCK_CREATE || event.type === Blockly.Events.BLOCK_DELETE) {
        updateVariableList();
      }

      if (event.type === Blockly.Events.VARIABLE_CREATE || event.type === Blockly.Events.VARIABLE_DELETE) {
        updateVariableList();
      }
    });

    // 初始化变量
    Blockly.Variables.createVariable(workspace, 'var1');
    Blockly.Variables.createVariable(workspace, 'var2');

    // 初始化变量列表
    updateVariableList();
  </script>
</body>
</html>
